/**
 * Created by TomSean on 2017/6/19.
 */
var ParkingLotEdit = function ($parent) {
    this.$parent = $parent;
    this.sysUtils = new kendoUtils();
    this.init();
    return this;
}
var SpaceDate = function(beginTime, deployMonth, endTime){ this.beginTime = beginTime; this.deployMonth = deployMonth; this.endTime = endTime };
ParkingLotEdit.prototype = {
    init : function () {
        var $this = this;
        $this.cache = new Map();
        var fieldArray = $this.sysUtils.getBindFieldArray($this.$parent.find('#parking_lot_edit_frame'));
        var functionArray = [
            {fName : 'buy_month', fs : $this.buyMonth},
            {fName : 'buy_store', fs : $this.buyStore},
            {fName : 'save_info', fs : $this.saveInfo}
        ];
        $this.models = new bindBaseModel(null, fieldArray, functionArray, null);
        $this.sysUtils.bindDoucment($this.models, $this.$parent, $this);
        $this.repository = {};
        // 查询所有分区
        JsonpAjax(baseApiPath + 'parking_space/potion/all', '', 'json', function(res) {
            $this.repository['potion'] = res;
        }, false);
        // 查询所有车辆类型
        $this.repository['vehicleType'] = Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT);
        Utils.createDataDictDropDownList({div : this.$parent.find('#charges-type'), unshift:true, parentModelKey : BASIS.CHARGE_METHOD.ROOT, select : Utils.getModelValueByModelKey(BASIS.CHARGE_METHOD.CASH)}, $this);
        $this.deployData();
    },
    buyStore : function(e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var date = new Date();
        var flag = 'new_'+date.getTime();
        $this.$parent.find('#month-card .no-data').remove();
        $this.$parent.find('.parking-lot center').remove();
        var org = $this.$parent.find('#org-module').clone();
        org.removeAttr('id');
        org.attr('id', flag);
        org.attr('data-type', 2);
        org.attr('data-space', flag);
        org.find('.page-1').hide();
        org.find('.page-2').show();
        org.removeClass('blue').addClass('green');
        org.find('.blue').each(function(inx, itm) {
            $(itm).removeClass('blue').addClass('green');
        });
        org.show();
        org.find('.potion-code .title').attr('data-value', $this.repository['potion'][0].code);
        org.find('.potion-code .title').html($this.repository['potion'][0].code);
        var potionTree = org.find('.potion-tree').lonixFloat({
            source: $this.repository['potion'],
            setting: {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data : {
                    simpleData: {
                        enable: true,
                        idKey: "code",
                        pIdKey: "pid",
                        rootPId:""
                    }
                }
            },
            searchField: 'name',
            target: org.find('.potion-code .title'),
            primary: function (nodes) {
                var node = nodes[0];
                org.find('.potion-code .title').html(node.name);
                org.find('.potion-code .title').attr('data-value', node.code);
                org.find('.potion-tree').fadeUp();
            }
        });
        $this.cache.put(flag, new SpaceDate(date.pattern("yyyy-MM-dd"), 1, date.pattern("yyyy-MM-dd")));
        org.find('.validate-time input').kendoDatePicker({
            format: "yyyy-MM-dd",
            value : date,
            change : function () {
                var cacheDate = $this.cache.get(flag);
                cacheDate['beginTime'] = this.value().pattern("yyyy-MM-dd");
                cacheDate['endTime'] = cacheDate['beginTime'];
                $this.cache.put(flag, cacheDate);
                $this.calMonth(org[0], flag);
            }
        });
        org.find('.validate-time input').attr('readonly','readonly');
        org.find('.type-code').html($this.repository['vehicleType'][0].modelValue)
        org.find('.type-code').lonixDownList({source:$this.repository['vehicleType'], title:'modelName', value:'modelValue'});
        $this.$parent.find('#month-card').append(org);
        $this.calMonth(org[0], flag);
        location.href='#' + flag;
    },
    deployData : function () {
        var $this = this;
        var entity = parkingSpace.entity;
        $this.ownerCode = parkingSpace.ownerCode;
        var vehicleList = entity[0];
        $this.vehicleList = vehicleList;
        var spaceList = entity[1];
        var chargesList = entity[2];
        if (chargesList.length == 0) {
            $this.$parent.find('.item-list-content').html('<center><p style="margin-top:100px;font-size:16px;font-weight:100;">暂未有任何消费记录</p></center>');
        } else {
            for (var i = 0; i < chargesList.length; i++) {
                var itemNode = '';
                var node = chargesList[i];
                var dateTime = node.chargeTime+'';
                var date = dateTime.split(' ');
                date[1] = date[1].substring(0, date[1].lastIndexOf(':'));
                if (isEmpty(node)) continue;
                itemNode += '<div class="item-list-node">';
                var remark = isEmpty(node.remark) ? ' 暂无备注' : node.remark;
                switch (node.payType+'') {
                    case Utils.getModelValueByModelKey(BASIS.PAY_TYPE.MONTH_CHARGE) :
                        itemNode += '    <img class="node-img" src="images/buycar.png" />';
                        itemNode += '    <p class="node-title">车位缴费</p>';
                        itemNode += '    <time class="node-date">'+date[0]+'</time>';
                        itemNode += '    <span style="font-size:12px;color:#666;position:absolute; top:0px; left:155px;">'+date[1]+'</span>';
                        itemNode += '    <p class="node-content" title="'+remark+'">'+remark+'</p>';
                        break;
                    case Utils.getModelValueByModelKey(BASIS.PAY_TYPE.SAVE_CHARGE) :
                        itemNode += '    <img class="node-img" src="images/buycar.png" />';
                        itemNode += '    <p class="node-title">预存金额</p>';
                        itemNode += '    <time class="node-date">'+date[0]+'</time>';
                        itemNode += '    <span style="font-size:12px;color:#666;position:absolute; top:0px; left:155px;">'+date[1]+'</span>';
                        itemNode += '    <p class="node-content" title="'+remark+'">'+remark+'</p>';
                        break;
                    case Utils.getModelValueByModelKey(BASIS.PAY_TYPE.TIMEOUT_CHARGE) :
                        itemNode += '    <img class="node-img" src="images/buycar.png" />';
                        itemNode += '    <p class="node-title">超时补缴</p>';
                        itemNode += '    <time class="node-date">'+date[0]+'</time>';
                        itemNode += '    <span style="font-size:12px;color:#666;position:absolute; top:0px; left:155px;">'+date[1]+'</span>';
                        itemNode += '    <p class="node-content" title="'+remark+'">'+remark+'</p>';
                        break;
                    default :
                        itemNode += '    <img class="node-img" src="images/buycar.png" />';
                        itemNode += '    <p class="node-title">其他缴费</p>';
                        itemNode += '    <time class="node-date">'+date[0]+'</time>';
                        itemNode += '    <span style="font-size:12px;color:#666;position:absolute; top:0px; left:155px;">'+date[1]+'</span>';
                        itemNode += '    <p class="node-content" title="'+remark+'">'+remark+'</p>';
                        break;
                }
                itemNode += '</div>';
                $this.$parent.find('.item-list-content').append(itemNode);
            }
        }
        $this.$parent.find('.owner-name').html(entity[3].ownerName);
        $this.$parent.find('#have-space .value').html(spaceList.length);
        $this.$parent.find('#have-vehicle .value').html(vehicleList.length);
        if (vehicleList.length > 0) {
            $this.$parent.find('#have-vehicle').addClass('lonix f-pop');
            var vehicleStr = '';
            for (var i = 0; i < vehicleList.length; i++) {
                vehicleStr += vehicleList[i].vehicleNo+'<br>';
            }
            var pop = '<div class="lonix f-pop-content" style="top:'+$this.$parent.find('#have-vehicle').height()+'px">'+vehicleStr+'</div>';
            $this.$parent.find('#have-vehicle').append(pop);
        }
        if ( vehicleList.length == 0 ) {
            notification({'title':'警告', 'message':'注意！当前车主还没有车辆信息，购置车位后无法通过车牌识别进入！'}, 'info');
        }
        var monthCard = $this.$parent.find('#month-card');
        var cacheSpaceCode = '';
        var sp = '';
        var date = new Date().pattern("yyyy-MM-dd");
        for (var i = 0; i < spaceList.length; i++) {
            if (cacheSpaceCode == '') { sp = 'sp1'; }
            else { sp = 'sp2'; }
            var org;
            if (cacheSpaceCode != spaceList[i].spaceCode) {
                cacheSpaceCode = spaceList[i].spaceCode;
                org = $this.$parent.find('#org-module').clone(false);
                org.removeAttr('id');
                org.attr('data-space', cacheSpaceCode);
                org.find('> .org-panel-title div').html(spaceList[i].spaceCode);
                org.find('> .org-panel-title div').removeAttr('contenteditable');
                org.find('.org-panel-title small').html('<span class="cur-begin-time">' + new Date(spaceList[i].beginTime).pattern("yyyy-MM-dd") + '</span>~<span class="cur-end-time">' + new Date(spaceList[i].endTime).pattern("yyyy-MM-dd") + '</span>');
                org.find('.org-content .space-type span').html(Utils.getModelNameByParentKey(BASIS.VEHICLE_TYPE.ROOT, spaceList[i].spaceType));
                org.find('.org-content .partition-code span').html(spaceList[i].partitionName);
                org.find('.org-content .potion-code .title').html(spaceList[i].partitionCode);
                org.find('.org-content .potion-code .title').attr('data-value', spaceList[i].partitionCode);
                org.find('.org-content .page-2 .ztree').attr('id', 'ztree-' + cacheSpaceCode + new Date().getDate());
                org.find('.org-line:eq(0) span').addClass(sp);
                org.find('.renewal-card').hide();
                var diffT = (new Date() - new Date(spaceList[i].endTime)) / 1000 / 3600 / 24;
                var daoqiData = '';
                org.find('.validate-time').hide();
                var tempTime = new Date(spaceList[i].beginTime);
                var afterEndTime = new Date(spaceList[i].endTime);
                if (diffT < 0) {
                    daoqiData = ('剩余' + Math.ceil(Math.abs(diffT)) + '天');
                } else if (diffT == 0) {
                    daoqiData = ('<span style="color:red">今天将过期！</span>');
                } else {
                    daoqiData = ('<span style="color:red">已过期' + Math.ceil(Math.abs(diffT)) + '天</span>');
                    org.find('.validate-time input').kendoDatePicker({
                        format: "yyyy-MM-dd",
                        value: date,
                        change: function () {
                            var cacheDate = $this.cache.get(cacheSpaceCode);
                            cacheDate['beginTime'] = this.value().pattern("yyyy-MM-dd");
                            cacheDate['endTime'] = cacheDate['beginTime'];
                            $this.cache.put(cacheSpaceCode, cacheDate);
                            $this.calMonth(org[0], cacheSpaceCode);
                        }
                    });
                    org.find('.validate-time input').attr('readonly','readonly');
                    org.find('.validate-time').show();
                    tempTime = new Date(date);
                    afterEndTime = tempTime;
                }
                $this.cache.put(cacheSpaceCode, new SpaceDate(tempTime.pattern("yyyy-MM-dd"), 1, afterEndTime.pattern("yyyy-MM-dd")));
                $this.calMonth(org[0], cacheSpaceCode);
                org.find('.card-blance .unit').html(daoqiData);
                monthCard.find('.no-data').remove();
            }
            org.find('.type-code').html($this.repository['vehicleType'][0].modelValue);
            monthCard.find('.no-data').remove();
            monthCard.append(org);
            org.show();
        }
        $this.$parent.find('.org-panel').each(function(inx, itm) {
            var potionTree = $(itm).find('.potion-tree').lonixFloat({
                source: $this.repository['potion'],
                setting: {
                    view: {
                        showLine: true,
                        selectedMulti: false,
                        dblClickExpand: false,
                        showIcon: false
                    },
                    data : {
                        simpleData: {
                            enable: true,
                            idKey: "code",
                            pIdKey: "pid",
                            rootPId:""
                        }
                    }
                },
                searchField: 'name',
                target: $(itm).find('.potion-code .title'),
                primary: function (nodes) {
                    var node = nodes[0];
                    $(itm).find('.potion-code .title').html(node.name);
                    $(itm).find('.potion-code .title').attr('data-value', node.code);
                    $(itm).find('.potion-tree').fadeUp();
                }
            });

            $(itm).find('.type-code').lonixDownList({source:$this.repository['vehicleType'], title:'modelName', value:'modelValue'});

        });
        JsonpAjax(baseApiPath + 'parking_space/relation?ownerCode=' + parkingSpace.ownerCode, '', 'json', function (res) {
            $this.relation = res;
            $this.reloadVehicle();
            if (isEmpty(res)) { return; }
            var org;
            cacheSpaceCode = '';
            for (var i = 0; i < res.length; i++) {
                if (cacheSpaceCode != res[i].parkingSpace.spaceCode) {
                    cacheSpaceCode = res[i].parkingSpace.spaceCode;
                    org = $this.$parent.find('.org-panel[data-space="'+cacheSpaceCode+'"]');
                    org.attr('data-type', res[i].trafficPermitInfo.trafficType);
                    org.find('.renewal-card').show();
                    if (res[i].trafficPermitInfo.trafficType == 1) {
                        org.find('.org-panel.vehicle .bottom-flag span').html('月卡车');
                    } else if (res[i].trafficPermitInfo.trafficType == 2) {
                        org.find('.org-panel.vehicle .bottom-flag span').html('储值卡');
                        org.removeClass('blue').addClass('green');
                        org.find('.blue').each(function(inx, itm){
                            $(itm).removeClass('blue').addClass('green');
                        });
                    }
                }
                org.find('.org-panel.vehicle ul').append('<li><a href="javascript:void(0)" class="delete-vehicle" onclick="parkingLotEdit.removeVehicle(this, event)"><img src="images/icon_off.png" /></a><a href="javascript:void(0)">'+res[i].vehicleNo+'</a></li>');
            }
        }, false);
    },
    reloadVehicle : function(){
        this.$parent.find('.add-vehicle-list ul').html('');
        var res = this.relation;
        for (var i = 0; i < this.vehicleList.length; i++) {
            var neutral = true;
            for (var j = 0; j < res.length; j++) {
                if (res[j].vehicleNo == this.vehicleList[i].vehicleNo) {
                    if (res[j].trafficPermitInfo.trafficType == 1) {
                        this.$parent.find('.add-vehicle-list ul').append(
                            '<li data-type="1">' +
                            '    <a href="javascript:void(0);" onclick="parkingLotEdit.bindVehicleToSpace(this)">'+res[j].vehicleNo+'</a>' +
                            '</li>'
                        );
                        neutral = false;
                        break;
                    } else if (res[j].trafficPermitInfo.trafficType == 2) {
                        this.$parent.find('.add-vehicle-list ul').append(
                            '<li data-type="2">' +
                            '    <a href="javascript:void(0);" onclick="parkingLotEdit.bindVehicleToSpace(this)">'+res[j].vehicleNo+'</a>' +
                            '</li>'
                        );
                        neutral = false;
                        break;
                    }
                }
            }
            if (neutral) {
                this.$parent.find('.add-vehicle-list ul').append(
                    '<li >' +
                    '    <a href="javascript:void(0);" onclick="parkingLotEdit.bindVehicleToSpace(this)">'+this.vehicleList[i].vehicleNo+'</a>' +
                    '</li>'
                );
            }
        }
        this.$parent.find('.add-vehicle-list ul').append('<li class="return"><a href="javascript:void(0);" onclick="parkingLotEdit.hideCanAddVehicle()">返回</a> </li>');
    },
    removeVehicle : function (itm, event) {
        var $this = this;
        var vehicleNo = $(itm).parent().find('a:eq(1)').html();
        var spaceCode = $(itm).parents('.org-panel:eq(1)').attr('data-space');
        if ($this.$parent.find('.org-panel[data-space="'+spaceCode+'"] .org-panel.vehicle ul li').length == 1) {
            notification({'title':'提示', 'message':'不能解除所有绑定'}, 'error');
            return;
        }
        if (spaceCode.indexOf('new_')==-1) {
            JsonpAjax(baseApiPath + 'parking_space/unbind_vehicle_space?spaceCode=' + spaceCode + '&vehicleNo=' + vehicleNo, '', 'json', function(res){

            }, false);
        }
        var result = $this.$parent.find('.add-vehicle-list a:contains('+vehicleNo+')');
        if (result.length <= 1) {
            result.parent().removeAttr('data-type');
        }
        $(itm).parent().remove();
    },
    bindVehicleToSpace : function (itm) {
        var vehicleNo = $(itm).html();
        var $this = this;
        var type = $this.$parent.find('.org-panel[data-space="'+$this.bindId+'"]').attr('data-type');
        if (isEmpty(type)) {
            // type 为空的话，默认为月卡(1)
            type = 1;
        }
        $(itm).parent().attr('data-type', type);
        if ($this.$parent.find('.org-panel[data-space="'+$this.bindId+'"] .org-panel.vehicle ul:contains('+vehicleNo+')').length > 0) {
            notification({'title':'提示', 'message':'请勿重复绑定车辆'}, 'error');
            return;
        }
        if ($this.bindId.indexOf('new_')==-1) {
            JsonpAjax(baseApiPath + 'parking_space/bind_vehicle_space?spaceCode=' + $this.bindId + '&vehicleNo=' + vehicleNo + '&type='+type, '', 'json', function(res){

            }, false);
        }
        $this.$parent.find('.org-panel[data-space="'+$this.bindId+'"] .org-panel.vehicle ul').append('<li><a href="javascript:void(0)" class="delete-vehicle" onclick="parkingLotEdit.removeVehicle(this, event)"><img src="images/icon_off.png" /></a><a href="javascript:void(0)">'+vehicleNo+'</a></li>');
        $this.hideCanAddVehicle();
    },
    showCanAddVehicle : function (itm, event) {
        this.bindId = $(itm).parents('.org-panel:eq(1)').attr('data-space');
        var type = $(itm).parents('.org-panel:eq(1)').attr('data-type');
        this.$parent.find('.add-vehicle-list li').show();
        if (!isEmpty(type)) {
            this.$parent.find('.add-vehicle-list li').not('li[data-type="'+type+'"]').hide();
        }
        this.$parent.find('.add-vehicle-list li').not('li[data-type]').show();
        this.$parent.find('.add-vehicle-list').css({'top':event.clientY+'px', 'left':event.clientX+'px', 'display':'inline-block'});
    },
    hideCanAddVehicle : function (){
        this.$parent.find('.add-vehicle-list').hide();
        this.bindId = undefined;
    },
    removeSpace : function (a) {
        var code = $(a).parents('.org-panel').attr('data-space');
        var $this = this;
        if (code.indexOf('new_')==-1) {
            notification({'title':'警告', 'message':'删除车位后将会自动删除对应的车牌识别通行凭证及与车主的车位关联信息，且该操作无法撤回，是否确认删除？'}, 'confirm', {
                callback: function () {
                    $(a).attr('disabled', 'disabled');
                    var vehicleList = [];
                    $(a).parents('.org-panel:eq(0)').find('.org-panel.vehicle li').each(function (inx, itm) {
                        vehicleList.push($(itm).find('a:eq(1)').html());
                    });
                    JsonpAjax(baseApiPath + 'parking_space/delete?id='+code, undefined, 'json', function(res) {
                        var val = $this.$parent.find('#have-space .value').html();
                        val = parseInt(val) - 1;
                        $this.$parent.find('#have-space .value').html(val);
                        $(a).parents('.org-panel').remove();
                        for (var i = 0; i < vehicleList.length; i++) {
                            if ($this.$parent.find('.org-panel.vehicle a:contains('+vehicleList[i]+')').length == 0) {
                                $this.$parent.find('.add-vehicle-list a:contains('+vehicleList[i]+')').parent().removeAttr('data-type');
                            }
                        }
                    }, false);
                }
            });
        } else {
            $(a).parents('.org-panel').remove();
        }
        $this.$parent.find('.buy-list-body-row .serial-number[data-value="'+code+'"]').parents('.buy-list-body-row').find('.delete-cur-data').trigger('click');
    },
    returnInfo: function (that) {
        $(that).parents('.org-panel').find('.page-1').fadeIn('fast');
        $(that).parents('.org-panel').find('.page-2').fadeOut('fast');
    },
    buyMonth : function (e) {
        var date = new Date();
        var flag = 'new_'+date.getTime();
        var $this = this;
        if (!isEmpty(e)) $this = $(e.target).data('that');
        $this.$parent.find('#month-card .no-data').remove();
        $this.$parent.find('.parking-lot center').remove();
        var org = $this.$parent.find('#org-module').clone();
        org.removeAttr('id');
        org.attr('data-type', 1);
        org.attr('id', flag);
        org.attr('data-space', flag);
        org.find('.page-1').hide();
        org.find('.page-2').show();
        org.find('.return-info').remove();
        $this.cache.put(flag, new SpaceDate(date.pattern("yyyy-MM-dd"), 1, date.pattern("yyyy-MM-dd")));
        org.find('.validate-time input').kendoDatePicker({
            format: "yyyy-MM-dd",
            value : date,
            change : function () {
                var cacheDate = $this.cache.get(flag);
                cacheDate['beginTime'] = this.value().pattern("yyyy-MM-dd");
                cacheDate['endTime'] = cacheDate['beginTime']
                $this.cache.put(flag, cacheDate);
                $this.calMonth(org[0], flag);
            }
        });
        org.find('.validate-time input').attr('readonly','readonly');
        org.find('.potion-code .title').attr('data-value', $this.repository['potion'][0].code);
        org.find('.potion-code .title').html($this.repository['potion'][0].code);
        var potionTree = org.find('.potion-tree').lonixFloat({
            source: $this.repository['potion'],
            setting: {
                view: {
                    showLine: true,
                    selectedMulti: false,
                    dblClickExpand: false,
                    showIcon: false
                },
                data : {
                    simpleData: {
                        enable: true,
                        idKey: "code",
                        pIdKey: "pid",
                        rootPId:""
                    }
                }
            },
            searchField: 'name',
            target: org.find('.potion-code .title'),
            primary: function (nodes) {
                var node = nodes[0];
                org.find('.potion-code .title').html(node.name);
                org.find('.potion-code .title').attr('data-value', node.code);
                org.find('.potion-tree').fadeUp();
            }
        });
        $this.$parent.find('#month-card').append(org);
        org.show();
        $this.calMonth(org[0], flag);
        org.find('.type-code').html($this.repository['vehicleType'][0].modelValue)
        org.find('.type-code').lonixDownList({source:$this.repository['vehicleType'], title:'modelName', value:'modelValue'});
        location.href='#' + flag;
    },
    renewalCard : function (that) {
        $(that).parents('.org-panel').find('.page-1').fadeOut('fast');
        $(that).parents('.org-panel').find('.page-2').fadeIn('fast');
    },
    calMonth : function(itm, code) {
        var beginTimeStr = this.cache.get(code).beginTime;
        var endTimeStr = this.cache.get(code).endTime;
        var deployMonth = this.cache.get(code).deployMonth;
        var beforeBeginTime = new Date(beginTimeStr);
        var beforeEndTime = new Date(endTimeStr);
        var endTime = new Date(endTimeStr);
        endTime.setMonth(endTime.getMonth() + deployMonth);
        if (beforeEndTime.getDate() != endTime.getDate()) {
            endTime.setDate(beforeEndTime.getDate()-(endTime.getDate()));
            endTime.setMonth(endTime.getMonth()-1);
        } else {
            var beginDate = new Date(beforeEndTime.getFullYear(), beforeEndTime.getMonth()+1, 0);
            var endDate = new Date(endTime.getFullYear(), endTime.getMonth()+1, 0);
            if ((beginDate.getDate() == beforeEndTime.getDate() && endDate.getDate() != endTime.getDate()) ) {
                endTime.setDate(endDate.getDate());
            } else if (beforeBeginTime.pattern('yyyy-M-d')==beforeEndTime.pattern('yyyy-M-d') && beforeBeginTime.getDate()==1) {
                endTime.setDate(0);
            }
        }
        $(itm).find('.begin-time').html(beginTimeStr);
        $(itm).find('.end-time').html(endTime.pattern('yyyy-MM-dd'));
    },
    preferential : function (temp) {
        var $this = this;
        JsonpAjax(baseApiPath + "preferential/valid", undefined, "json", function(data) {
            data.unshift({preferentialCode : -1, preferentialName:"不使用优惠"});
            if (data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var option = '<option value="'+data[i].preferentialCode+'">'+data[i].preferentialName+'</option>';
                    if (isNotEmpt(data[i].merchant)) {
                        var opt = $this.$parent.find('#m-'+data[i].merchant.id);
                        if (opt.length > 0) {
                            opt.append(option);
                        } else {
                            opt = $('<optgroup label="'+data[i].merchant.merchantName+'" id="m-'+data[i].merchant.id+'"></optgroup>');
                            opt.append(option);
                            $(temp).find('.node-preferential select').append(opt);
                        }
                    } else {
                        $(temp).find('.node-preferential select').append(option);
                    }
                }
                $(temp).find('.node-preferential select').bind('change', function (event) {
                    var preferential = $(this).val();
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].preferentialCode == $(this).val()) {
                            preferential = data[i];
                            break;
                        }
                    }
                    if (preferential.preferentialCode == '-1') {
                        $(temp).find('.node-price').css({'text-decoration':'none'});
                        $(temp).find('.preferential-price').hide();
                        $(temp).find('.preferential-price').html($(temp).find('.node-price').html());
                    } else {
                        $(temp).find('.node-price').css({'text-decoration':'line-through'});
                        $(temp).find('.preferential-price').show();
                        var sourcesPrice = $(temp).find('.node-price').html();
                        var preferentialPrice = 0;
                        if (preferential.preferentialType == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.CASH_TICKET)) {
                            preferentialPrice = parseFloat(sourcesPrice)-parseFloat(preferential.preferentialContent);
                        } else if (preferential.preferentialType == Utils.getModelValueByModelKey(BASIS.PREFERENTIAL_TYPE.DISCOUNT)) {
                            preferentialPrice = parseFloat(sourcesPrice)*parseFloat(preferential.preferentialContent*0.1);
                        } else {
                            preferentialPrice = sourcesPrice;
                        }
                        if (preferentialPrice < 0) {
                            preferentialPrice = 0.0;
                        }
                        $(temp).find('.preferential-price').html(preferentialPrice.toFixed(2));
                    }
                    var savePrice = 0;
                    var totalPrice = 0;
                    $this.$parent.find('.buy-list-body-row').not('#buy-list-row-template').each(function (inx, itm) {
                        totalPrice += parseFloat($(itm).find('.node-price').html());
                        savePrice += parseFloat($(itm).find('.preferential-price').html());
                    });
                    var resultPrice = totalPrice - savePrice;
                    $this.$parent.find('.save-price').html(resultPrice < 0 ? 0 : resultPrice);
                    $this.$parent.find('.total-price').html(savePrice);
                });
                $(temp).find('.node-preferential select').change();
            }
        }, false);
    },
    saveInfo : function (e) {
        var $this = this;
        if (!isEmpty(e)) {
            $this = $(e.target).data('that');
        }
        var spaceList = [];
        var fail = false;
        $this.$parent.find('.buy-list-body-row:visible').each(function (inx, itm) {
            var space = {};
            var price = $(itm).find('.node-price').html();
            var vehicleType = $(itm).find('.vehicle-type').attr('data-value');
            var serialNumber = $(itm).find('.serial-number').html();
            var spaceCode = $(itm).find('.space-code').val();
            var cardType = $(itm).find('.card-type').val();
            if (serialNumber.indexOf('new_') != -1) {
                space['isNew'] = 'true';
            }
            var preferentialId = $(itm).find('.node-preferential select').val();
            var beginTime = $(itm).find('.begin-time').val();
            var endTime = $(itm).find('.end-time').val();
            var partitionCode = $(itm).find('.partition-code').val();
            var chargesCode = $(itm).find('.toll-standard select').val();
            var month = $(itm).find('.buy-count').attr('data-value');
            space['total'] = price;
            space['spaceCode'] = spaceCode;
            space['spaceType'] = vehicleType;
            space['partitionCode'] = partitionCode;
            space['beginTime'] = beginTime;
            space['endTime'] = endTime;
            space['preferentialId'] = preferentialId;
            space['month'] = month;
            space['cardType'] = cardType;
            space['chargesCode'] = chargesCode;
            var vehicleNoArray = [];
            $this.$parent.find('.org-panel[data-space="'+serialNumber+'"] .org-panel.vehicle li').each(function(inx, itm) {
                vehicleNoArray.push($(itm).find('a:eq(1)').html());
            });
            if (vehicleNoArray.length == 0) {
                notification({'title':'提示', 'message':'有车位没有绑定车辆，为无效车位，请先给所有车位绑定车辆！'}, 'error');
                fail = true;
                return;
            }
            space['vehicleArray'] = vehicleNoArray;
            spaceList.push(space);
        });
        if (fail) {
            return;
        }
        var listInfo = {};
        listInfo['ownerCode'] = $this.ownerCode;
        listInfo['chargesMethod'] = $this.$parent.find('#charges-type').val();
        listInfo['spaceList'] = spaceList;
        var dataT = listInfo;
        JsonpAjax(baseApiPath + 'parking_space/save', JSON.stringify(dataT), 'json', function (res) {
            $('#' + parkingSpace.editDiv).data('kendoWindow').close();
            parkingSpace.findData();
        }, false);
    },
    parkingLotEditChangeMonthEvent : function (that) {
        var code = $(that).parents('.org-panel').attr('data-space');
        parkingLotEdit.cache.get(code)['deployMonth'] = parseInt(isEmpty($(that).val()) ? 0 : $(that).val());
        console.log(parkingLotEdit.cache.get(code)['deployMonth']);
        parkingLotEdit.calMonth($(that).parents('.org-panel'), code);
    },
    parkingLotEditAddToBuyList : function (that) {
        // 取值
        var dis = $(that).hasClass('disabled');
        if (dis) {
            return;
        }
        var $space = $(that).parents('.org-panel');
        var cardType = $space.attr('data-type');
        // 克隆模板
        var template = parkingLotEdit.$parent.find('#buy-list-row-template').clone(false);
        template.find('.card-type').val(cardType);
        var spaceType = $space.find('.type-code .title').attr('data-value');
        var potionCode = $space.find('.potion-code .title').attr('data-value');
        var beginTime = $space.find('.begin-time').html();
        var endTime = $space.find('.end-time').html();
        var spaceCode = $space.find('.org-panel-title div').html();
        var patrn=/^(\w){2,10}$/;
        if (!isEmpty(spaceCode) && !patrn.exec(spaceCode)) {
            
        }
        var payProject = '';
        var serialNumber = '';
        var deployMonth = $space.find('.delay-time input').val();
        if (isNaN(deployMonth) || deployMonth <= 0 || deployMonth > 999) {
            notification({title:'错误', message:'月份必须是正确的数字且小于999'}, 'error');
            return;
        }
        var remark = '有效期：'+beginTime + ' ~ ' + endTime;
        serialNumber = $space.attr('data-space');

        // 去掉template标识
        template[0].id = undefined;
        // 赋值
        template.find('.serial-number').attr('data-value', serialNumber);
        template.find('.serial-number').html(serialNumber);

        if (cardType == 1) {
            if ($space.attr('data-flag')) {
                payProject = '新购 {'+$space.find('.potion-code .title').html()+'} 月卡';
            } else {
                payProject = '续期月卡 {'+$space.find('.potion-code .title').html()+'} ['+serialNumber+']';
            }
            var fail = false;
            var curChargesCode = '';
            JsonpAjax(baseApiPath + 'parking_space/charges/get?potionCode='+potionCode+'&vehicleType='+spaceType, '', 'json', function(res) {
                if (!isEmpty(res)) {
                    if (isEmpty(res.chargeStandardInfos) || isEmpty(res.chargeStandardInfos.A)) {
                        notification({title:'提示', message:'当前分区暂无收费标准，添加失败'}, 'info');
                        fail = true;
                        return;
                    }
                    curChargesCode = res.chargeCode;
                    var shouFeiBiaoZhun = parseFloat(res.chargeStandardInfos.A.payMoney);
                    shouFeiBiaoZhun = shouFeiBiaoZhun * deployMonth;
                    template.find('.node-price').html(shouFeiBiaoZhun);
                    var totalPrice = parkingLotEdit.$parent.find('.total-price').html();
                    totalPrice = parseFloat(totalPrice);
                    totalPrice += shouFeiBiaoZhun;
                    parkingLotEdit.$parent.find('.total-price').html(totalPrice);
                }
            }, false);
            var options = '<option value="-1">暂无收费标准</option>';
            JsonpAjax(baseApiPath + 'parking_space/charges/all', undefined, 'json', function(res) {
                if (!isEmpty(res)) {
                    options = '';
                    for (var i = 0; i < res.length; i++) {
                        options += '<option value="'+res[i].code+'" data-money="'+res[i].payMoney+'">'+res[i].name+'</option>';
                    }
                }
            }, false);
            template.find('.toll-standard select').html(options);
            template.find('.toll-standard select').val(curChargesCode);
            if (fail) return;
        } else if (cardType==2) {
            if ($space.attr('data-flag')) {
                payProject = '储值卡新购 {'+$space.find('.potion-code .title').html()+'} ';
            } else {
                payProject = '储值卡修改 {'+$space.find('.potion-code .title').html()+'} ['+serialNumber+']';
            }
            // 去掉template标识
            // 赋值
            template.find('.buy-count').html('￥'+0);
            template.find('.buy-count').attr('data-value', 0);
            template.find('.node-preferential input');
            template.find('.node-price').html(0);
            template.find('.toll-standard').html('自定义金额');
        }
        template.find('.begin-time').val(beginTime);
        template.find('.end-time').val(endTime);
        template.find('.space-code').val(spaceCode);
        template.find('.partition-code').val(potionCode);
        template.find('.pay-project').html(payProject);
        template.find('.remark').html(remark);
        template.find('.buy-count').html(deployMonth+'个月');
        template.find('.buy-count').attr('data-value', deployMonth);
        template.find('.vehicle-type').attr('data-value', spaceType);
        template.find('.vehicle-type').html($space.find('.space-type .title').html());

        template.find('.delete-cur-data').unbind('click').bind('click', function(event) {
            var count = parkingLotEdit.$parent.find('.total-goods span').html();
            count = parseInt(count) - 1;
            parkingLotEdit.$parent.find('.total-goods span').html(count);
            var s = $(this).parents('.buy-list-body-row').find('.serial-number').html();
            parkingLotEdit.$parent.find('[data-space="'+serialNumber+'"] .add-buy-list').html('添加到清单');
            parkingLotEdit.$parent.find('[data-space="'+serialNumber+'"] .add-buy-list').removeClass('disabled');
            parkingLotEdit.$parent.find('[data-space="'+serialNumber+'"] .add-buy-list').removeAttr('disabled');
            $(this).parents('.buy-list-body-row').remove();
            var savePrice = 0;
            var totalPrice = 0;
            parkingLotEdit.$parent.find('.buy-list-body-row').not('#buy-list-row-template').each(function (inx, itm) {
                totalPrice += parseFloat($(itm).find('.node-price').html());
                savePrice += parseFloat($(itm).find('.preferential-price').html());
            });
            var resultPrice = totalPrice - savePrice;
            parkingLotEdit.$parent.find('.save-price').html(resultPrice < 0 ? 0 : resultPrice);
            parkingLotEdit.$parent.find('.total-price').html(savePrice);
            if (parkingLotEdit.$parent.find('.buy-list-body-row:visible').length == 0) {
                parkingLotEdit.$parent.find('.buy-list-body').prepend('<p id="nothing" style="float:left;width:100%; font-size:22px; text-align:center; margin:20px 0;font-weight:100;">暂未有任何缴费清单</p>');
            }
        });
        $(template).show();
        parkingLotEdit.$parent.find('.buy-list-body').prepend(template);
        parkingLotEdit.$parent.find('.buy-list-body #nothing').remove();
        $(that).attr('disabled', 'disabled');
        $(that).addClass('disabled');
        $(that).html('已添加到清单');
        var count = parkingLotEdit.$parent.find('.total-goods span').html();
        count = parseInt(count) + 1;
        parkingLotEdit.$parent.find('.total-goods span').html(count);
        parkingLotEdit.preferential(template);
    }
};
function parkingLotEditChangeTollStandard (that) {
    var money = $(that).find('option:selected').attr('data-money');
    var $nodePrice = $(that).parents('.buy-list-body-row').find('.node-price');
    var month = $(that).parents('.buy-list-body-row').find('.buy-count').attr('data-value');
    var $preferential = $(that).parents('.buy-list-body-row').find('.node-preferential select');
    $nodePrice.html(money * month);
    $preferential.change();
    var savePrice = 0;
    var totalPrice = 0;
    parkingLotEdit.$parent.find('.buy-list-body-row').not('#buy-list-row-template').each(function (inx, itm) {
        totalPrice += parseFloat($(itm).find('.node-price').html());
        savePrice += parseFloat($(itm).find('.preferential-price').html());
    });
    parkingLotEdit.$parent.find('.save-price').html(totalPrice - savePrice);
    parkingLotEdit.$parent.find('.total-price').html(savePrice);
}